package com.eduplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eduplatform.dto.ExamPaperDTO;
import com.eduplatform.entity.Exam;
import com.eduplatform.entity.ExamPaper;
import com.eduplatform.entity.School;
import com.eduplatform.entity.Subject;
import com.eduplatform.entity.User;
import com.eduplatform.mapper.ExamMapper;
import com.eduplatform.mapper.ExamPaperMapper;
import com.eduplatform.mapper.SchoolMapper;
import com.eduplatform.mapper.SubjectMapper;
import com.eduplatform.mapper.UserMapper;
import com.eduplatform.service.ExamPaperService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 考试答卷服务实现类
 */
@Service
public class ExamPaperServiceImpl extends ServiceImpl<ExamPaperMapper, ExamPaper> implements ExamPaperService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private SubjectMapper subjectMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Override
    public IPage<ExamPaperDTO> pageExamPapers(int page, int size, Long examId, Long subjectId,
            Integer educationLevel, Long schoolId, String studentName) {
        Page<ExamPaper> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<ExamPaper> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        if (examId != null) {
            wrapper.eq(ExamPaper::getExamId, examId);
        }

        if (schoolId != null) {
            wrapper.eq(ExamPaper::getSchoolId, schoolId);
        }

        if (educationLevel != null) {
            // 通过考试ID查询考试信息，获取教育阶段
            if (examId != null) {
                Exam exam = examMapper.selectById(examId);
                if (exam != null && exam.getEducationLevel() != null) {
                    wrapper.eq(ExamPaper::getExamId, examId);
                }
            } else {
                // 通过科目ID查询科目信息，获取教育阶段
                if (subjectId != null) {
                    Subject subject = subjectMapper.selectById(subjectId);
                    if (subject != null && subject.getLevel() != null) {
                        wrapper.inSql(ExamPaper::getExamId, "SELECT id FROM exam WHERE subject_id = " + subjectId);
                    }
                }
            }
        }

        // 学生姓名模糊查询
        if (StringUtils.hasText(studentName)) {
            wrapper.inSql(ExamPaper::getStudentId, "SELECT id FROM user WHERE nickname LIKE '%" + studentName + "%'");
        }

        // 按提交时间降序排序
        wrapper.orderByDesc(ExamPaper::getSubmitTime);

        // 分页查询
        Page<ExamPaper> result = this.page(pageParam, wrapper);

        // 转换为DTO
        List<ExamPaperDTO> examPaperDTOs = result.getRecords().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());

        // 构建返回结果
        Page<ExamPaperDTO> dtoPage = new Page<>();
        BeanUtils.copyProperties(result, dtoPage, "records");
        dtoPage.setRecords(examPaperDTOs);

        return dtoPage;
    }

    @Override
    public ExamPaperDTO getExamPaperDetail(Long id) {
        ExamPaper examPaper = this.getById(id);
        if (examPaper == null) {
            return null;
        }
        return convertToDTO(examPaper);
    }

    /**
     * 将ExamPaper实体转换为DTO
     */
    private ExamPaperDTO convertToDTO(ExamPaper examPaper) {
        ExamPaperDTO dto = new ExamPaperDTO();
        BeanUtils.copyProperties(examPaper, dto);

        // 获取考试信息
        Exam exam = examMapper.selectById(examPaper.getExamId());
        if (exam != null) {
            dto.setExamName(exam.getTitle());
            dto.setEducationLevel(exam.getEducationLevel());

            // 获取科目信息
            Long examSubjectId = exam.getSubjectId();
            if (examSubjectId != null) {
                Subject subject = subjectMapper.selectById(examSubjectId);
                if (subject != null) {
                    dto.setSubjectId(subject.getId());
                    dto.setSubjectName(subject.getName());
                }
            }
        }

        // 获取学生信息
        User student = userMapper.selectById(examPaper.getStudentId());
        if (student != null) {
            dto.setStudentName(student.getNickname());
        }

        // 获取学校信息
        School school = schoolMapper.selectById(examPaper.getSchoolId());
        if (school != null) {
            dto.setSchoolName(school.getName());
        }

        return dto;
    }
}